package com.dckeji.shiplock.framework.util;


import com.dckeji.shiplock.framework.pojo.LockInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.InputStream;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: TianWei
 * Date: 2017/8/18
 * Time: 10:36
 */
public class ExcelUtil {


    public static Map<String, String> getMap(String keyValue) {
        Map<String, String> map = new HashMap<String, String>();
        if (keyValue != null) {
            String[] str = keyValue.split(",");
            for (int i = 0; i < str.length; i++) {
                String[] str2 = str[i].split(":");
                map.put(str2[0], str2[1]);
            }
        }
        return map;
    }

    public static void main(String[] args) throws Exception {
        String s = new LockInfo().execlMap();
        System.out.println(s);
        Map<String, String> map = getMap(s);

//        List<Object> objects = readXls("C:\\Users\\Administrator\\Desktop\\解台船闸\\闸次信息20170726.xls", map, "com.dckeji.shiplock.framework.pojo.LockInfo");
//        for (Object lockInfo : objects) {
//            LockInfo lock = (LockInfo) lockInfo;
//            System.out.println(lock.getLockType());
//        }

    }

    public static List<Object> readXls(String fileName, InputStream inputStream, Map map,
                                       Class<?> demo) throws Exception {
        Set keySet = map.keySet();// 返回键的集合

        /** 反射用 **/
        Object obj = null;
        /** 反射用 **/

        List<Object> list = new ArrayList<Object>();
        String fileType = fileName.substring(fileName.lastIndexOf(".") + 1,
                fileName.length());
        InputStream is = inputStream;
        Workbook wb = null;

        if (fileType.equals("xls")) {
            wb = new HSSFWorkbook(is);
        } else if (fileType.equals("xlsx")) {
            wb = new XSSFWorkbook(is);
        } else {
            System.out.println("[ExcelUtil Error Message]:您输入的excel格式不正确");
        }
        lableBreak:
        for (int sheetNum = 0; sheetNum < wb.getNumberOfSheets(); sheetNum++) {// 获取每个Sheet表

            int rowNum_x = -1;// 记录第x行为表头
            Map<String, Integer> cellmap = new HashMap<String, Integer>();// 存放每一个field字段对应所在的列的序号

            Sheet hssfSheet = wb.getSheetAt(sheetNum);

            // 循环行Row
            for (int rowNum = 0; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                Row hssfRow = hssfSheet.getRow(rowNum);
                if (hssfRow == null) {
                    continue;
                }
                boolean flag = false;
                for (int i = 0; i < hssfRow.getLastCellNum(); i++) {
                    if (hssfRow.getCell(i) != null
                            && !("").equals(hssfRow.getCell(i).toString()
                            .trim())) {
                        flag = true;
                    }
                }
                if (!flag)
                    continue;

                if (rowNum_x == -1) {
                    // 循环列Cell
                    for (int cellNum = 0; cellNum <= hssfRow.getLastCellNum(); cellNum++) {

                        Cell hssfCell = hssfRow.getCell(cellNum);
                        if (hssfCell == null) {
                            continue;
                        }

                        String tempCellValue = "";
                        tempCellValue = hssfSheet.getRow(rowNum)
                                .getCell(cellNum).getStringCellValue().trim();
                        Iterator it = keySet.iterator();
                        while (it.hasNext()) {
                            Object key = it.next();
                            if (!("").equals(tempCellValue)
                                    && key.equals(tempCellValue)) {
                                rowNum_x = rowNum;
                                cellmap.put(map.get(key).toString(), cellNum);
                            }
                        }
                        if (rowNum_x == -1) {
                            System.out
                                    .println("[ExcelUtil Error Message]:没有找到对应的字段或者对应字段行上面含有不为空白的行字段");
                            break lableBreak;
                        }
                    }
                } else {
                    obj = demo.newInstance();
                    Iterator it = keySet.iterator();
                    while (it.hasNext()) {
                        Object key = it.next();
                        Integer cellNum_x = cellmap
                                .get(map.get(key).toString());
                        if (cellNum_x == null
                                || hssfRow.getCell(cellNum_x) == null) {
                            continue;
                        }
                        String attr = map.get(key).toString();
                        Class<?> attrType = demo.getDeclaredField(attr).getType();
                        Cell cell = hssfRow.getCell(cellNum_x);
                        getValue(cell, obj, attr, attrType);

                    }
                    list.add(obj);
                }

            }
        }
        // wb.close();
        return list;
    }


    public static void setter(Object obj, String att, Object value,
                              Class<?> type) {
        try {
            Method method = obj.getClass().getMethod("set" + toUpperCaseFirstOne(att), type);
            method.invoke(obj, value);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    public static void getValue(Cell cell, Object obj, String attr, Class attrType) {
        Object val = null;
        if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            val = cell.getBooleanCellValue();

        } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            if (DateUtil.isCellDateFormatted(cell)) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    if (attrType == String.class) {
                        val = sdf.format(DateUtil.getJavaDate(cell.getNumericCellValue()));
                    } else {
                        val = dateConvertFormat(sdf.format(DateUtil.getJavaDate(cell.getNumericCellValue())));
                    }
                } catch (ParseException e) {
                    System.out.println("日期格式转换错误");
                }
            } else {
                if (attrType == String.class) {
                    val = Double.toString(cell.getNumericCellValue());
                } else if (attrType == Float.class) {
                    val = (float) cell.getNumericCellValue();
                } else if (attrType == int.class) {
                    val = (int) cell.getNumericCellValue();
                } else {
                    val = cell.getNumericCellValue();
                }
            }

        } else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
            val = cell.getStringCellValue();
        }

        setter(obj, attr, val, attrType);
    }

    /**
     * 首字母转小写
     * @param s
     * @return
     */
    public static String toLowerCaseFirstOne(String s) {
        if (Character.isLowerCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder())
                    .append(Character.toLowerCase(s.charAt(0)))
                    .append(s.substring(1)).toString();
    }

    /**
     * 首字母转大写
     * @param s
     * @return
     */
    public static String toUpperCaseFirstOne(String s) {
        if (Character.isUpperCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder())
                    .append(Character.toUpperCase(s.charAt(0)))
                    .append(s.substring(1)).toString();
    }

    /**
     * String类型日期转为Date类型
     * @param dateStr
     * @return
     * @throws ParseException
     * @throws Exception
     */
    public static Date dateConvertFormat(String dateStr) throws ParseException {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        date = format.parse(dateStr);
        return date;
    }

}